<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Models\ReadDrawingQa;
use Illuminate\Support\Facades\Log;

class ReadDrawingQaService
{
    public function get($title)
    {
        $sql = ReadDrawingQa::when($title, function ($query, $title) {
            return $query->where(function($query) use ($title) {
                $query->where('name','like', '%'.$title.'%');
            });
        });
        return $sql;
    }

    public function batch($input)
    {
        $datas = json_decode($input['datas']);
        $insert = [];
        foreach ($datas as $k => $v) {
            if($k > 0){
                if(empty($v[0])){
                    throw new InvalidRequestException('第'.$k.'行部位不能为空');
                }
                $arr = [];
                $arr['name'] = $v[0];
                $arr['number'] = $v[1];
                $arr['brief'] = $v[2];
                $arr['drawing'] = $v[3];
                $arr['construction_unit'] = $v[4];
                $arr['design_unit'] = $v[5];
                $arr['supervision_unit'] = $v[6];
                $arr['remarks'] = $v[7];
                $arr['project_id'] = $input['project_id'];
                $arr['admin_id'] = $input['admin_id'];
                $arr['company_id'] = $input['company_id'];
                $insert[] = $arr;
            }
        }
        try {
            $data = ReadDrawingQa::insert($insert);
            //添加到人员库存
            if($data){
                return $data;
            }
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function insert($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }
        try {
            $data = ReadDrawingQa::create($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function update($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }
        unset($res['id']);
        try {
            $data = ReadDrawingQa::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

}